//
//  SearchViewController.m
//  B-72K
//
//  Created by sos on 16/3/17.
//  Copyright © 2016年 sos. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchModel.h"
#import "QPNetWorkingTool.h"
#import "SearchNewViewController.h"
#import <iflyMSC/IFlyMSC.h>
#import "ISRDataHelper.h"
#import "NewsTableViewCell.h"
#import "NewsModel.h"
#import "IATConfig.h"
#import "TimeChange.h"
#import "NewsViewController.h"
#import "NewsDetialViewController.h"
#import <MJRefresh.h>
#import "AllPrefixHeader.pch"

@interface SearchViewController ()<UISearchResultsUpdating, UISearchBarDelegate,UITableViewDataSource, UITableViewDelegate,IFlySpeechRecognizerDelegate>
@property (nonatomic, retain) UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, copy) NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain) NSMutableArray *companyArr;/**< 搜索到公司数组 */

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *tempView;
@property (nonatomic,strong) IFlySpeechRecognizer *iFlySpeechRecognizer;
@property (nonatomic, assign) NSInteger i;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar NightWithType:UIViewColorType1];
    
    // 创建tableView
    [self createTableView];
    
    // 初始化搜索视图
    self.search = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 签订协议
    _search.searchResultsUpdater = self;
    
    // 屏幕不变灰 yes时tableview 不能下拉
    _search.dimsBackgroundDuringPresentation = NO;
    
    // 设置点击搜索框时隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    
    // 位置自适应
    [_search.searchBar sizeToFit];
    
    //_search.searchBar.frame = CGRectMake(self.search.searchBar.frame.origin.x, self.search.searchBar.frame.origin.y, self.search.searchBar.frame.size.width, 44.0);
    
    
    
    
    
    // 把搜索视图加载导航栏上
    self.navigationItem.titleView = _search.searchBar;
    
    //self.tableView.tableHeaderView = self.search.searchBar;
    
    
//     创建右边搜索新闻按钮
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"huatong@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchNews:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"huatong@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchNews:)];
    
//    UIBarButtonItem *rightOne = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"huatong@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchNews:)];
//    
//    UIBarButtonItem *rightTwo = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(quxiao)];
//    self.navigationItem.rightBarButtonItems = @[rightOne,rightTwo];
    

    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    //创建语音识别
    [self createYuYin];
    
    _i = 2;
    
    // 上拉加载
    [self loading];
}

- (void)loading
{
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //延迟两秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news/search?keyword=%@&page=%ld&pageSize=20", _search.searchBar.text, _i];
            
//         
            [QPNetWorkingTool getNetWorkingTool:str dic:nil success:^(id result) {
                NSMutableArray *arr = result[@"data"][@"data"];
                                NSMutableArray *temp = [NewsModel modelHanderWithArray:arr];
                
                                for (NewsModel *m in temp) {
                                    [self.companyArr addObject:m];
                                }
                                
                                [_tableView reloadData];
                
                
            } fail:^(NSError *error) {
                
                
            }];
            _i++;
            [_tableView.mj_footer endRefreshing];
        });
    }];
    _tableView.mj_footer = footer;
}
//创建语音识别
-(void)createYuYin
{
    
    //单例模式，无UI的实例
    if (_iFlySpeechRecognizer == nil) {
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //设置听写模式
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    }
    _iFlySpeechRecognizer.delegate = self;
    
    if (_iFlySpeechRecognizer != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        
        //设置最长录音时间
        [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        //网络等待时间
        [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        
        //设置采样率，推荐使用16K
        [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE_16K]];
        
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            //设置语言
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        //设置是否返回标点符号
        [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT_NODOT]];
        
    }
    
    
}
-(void)searchNews:(NSString *)str
{
    [_search.searchBar becomeFirstResponder];
    if ([IATConfig sharedInstance].haveView == NO) {//无界面
        
        [_search.searchBar setText:@""];
        [_search.searchBar resignFirstResponder];
        //        self.isCanceled = NO;
        
        if(_iFlySpeechRecognizer == nil)
        {
            [self createYuYin];
        }
        
        [_iFlySpeechRecognizer cancel];
        
        //设置音频来源为麦克风
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置听写结果格式为json
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {
            //            [_audioStreamBtn setEnabled:NO];
            //            [_upWordListBtn setEnabled:NO];
            //            [_upContactBtn setEnabled:NO];
        }else{
            //            [_popUpView showText: @"启动识别服务失败，请稍后重试"];//可能是上次请求未结束，暂不支持多路并发
        }
    }else {
        
        //        if(_iflyRecognizerView == nil)
        {
            //            [self initRecognizer ];
        }
        
        [_search.searchBar setText:@""];
        [_search.searchBar resignFirstResponder];
        
        //设置音频来源为麦克风
        //        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置听写结果格式为json
        //        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
        //        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        //        [_iflyRecognizerView start];
    }
    
    
    [self performSelector:@selector(yanshi) withObject:self afterDelay:3];
    
}
-(void)yanshi
{
    [_iFlySpeechRecognizer stopListening];
        [self.search.searchBar resignFirstResponder];
}
-(void)createTableView{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView NightWithType:UIViewColorTypeNormal];

    [_tableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:@"cell"];
    
}
-(void)onResults:(NSArray *)results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    //    NSString *result =[NSString stringWithFormat:@"%@%@", _label.text,resultString];
   
  
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    NSString *ss = [resultFromJson stringByReplacingOccurrencesOfString:@"。" withString:@""];
    _search.searchBar.text = [NSString stringWithFormat:@"%@%@", _search.searchBar.text,ss];
    
}
-(void)onError:(IFlySpeechError *)errorCode
{
    
    NSLog(@"~~~~~~~~~~~~~~~~%@",errorCode);
    
}
#pragma mark - 实现搜索栏协议方法
// 知道搜索栏有内容 就执行下面的方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
   
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息
    self.strHight = [self.search.searchBar text];
    
    if ([_strHight containsString:@" "] || _strHight.length == 0) {
        
        // 字符串有空格的时候 搜索会崩溃
        // 判断如果有空格不执行
        // 没有执行以下程序
        
    } else {
        
        // 拼接
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        // 中文转码
        NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news/search?keyword=%@&page=1&pageSize=20", urlStr];
        
        [QPNetWorkingTool getNetWorkingTool:str dic:nil success:^(id result) {
            
            NSArray *arr = result[@"data"][@"data"];
            self.companyArr = [NewsModel modelHanderWithArray:arr];
            [_tableView reloadData];

            
            
        } fail:^(NSError *error) {
            
            
        }];
        
//        [QPNetWorkingTool postNetWorkingTool:str dic:nil success:^(id result) {
//            NSArray *arr = result[@"data"][@"company"];
//            self.companyArr = [SearchModel modelHanderWithArray:arr];
//            [_tableView reloadData];
//
//            
//        } fail:^(NSError *error) {
//            
//            
//            
//        }];
        
        
           }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _companyArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell NightWithType:UIViewColorTypeNormal];
    
    
    
    NewsModel *m = _companyArr[indexPath.row];
    
    ///高亮设置
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:m.title];
    NSRange range = [m.title rangeOfString:_search.searchBar.text];
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],   NSFontAttributeName : [UIFont systemFontOfSize:18]} range:range];
    
    cell.title.attributedText = attrituteString;
    cell.columName.text = m.columnName;
    cell.name.text = m.name;
    [cell.tu sd_setImageWithURL:[NSURL URLWithString:m.featureImg] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
    [cell.touxiang sd_setImageWithURL:[NSURL URLWithString:m.avatar]];
    cell.time.text = [TimeChange compareCurrentTime:m.publishTime];

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
        NewsModel *m = _companyArr[indexPath.row];
    NewsDetialViewController *detial = [[NewsDetialViewController alloc]init];
    detial.str = m.feedId;
    [self.navigationController pushViewController:detial animated:YES];
//    NewsDetailViewController *ndVC = [[ alloc] init];
    
//    ndVC.str = m.feedId;
    
//    [self.navigationController pushViewController:ndVC animated:YES];
    

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 165;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)back
{
 
//    
    self.search.active = NO;
    [self dismissViewControllerAnimated:YES completion:^{
//        [self quxiao];
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_iFlySpeechRecognizer stopListening];
    
}
//-(void)quxiao
//{
//    [self dismissViewControllerAnimated:YES completion:^{
//    }];
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
